package org.angelica.core.xss;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * XSS漏洞过滤
 * @author aizhimin
 */
public class XssFilter implements Filter {

	/**
	 * 跳过验证的请求uri
	 */
	private List<Pattern> excludeUris = new ArrayList<Pattern>();

	@Override
	public void init(FilterConfig config) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

		HttpServletRequest hsRequest = (HttpServletRequest)request;
		//如果是需要跳过的uri，则放行
		if(isExcludeUri(hsRequest.getRequestURI())) {
			chain.doFilter(request, response);
			return;
		}

		XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper(
				(HttpServletRequest) request);
		chain.doFilter(xssRequest, response);
	}

	@Override
	public void destroy() {
	}

	/**
	 * 判断是否是排除过滤的URI
	 * @param requestUri
	 * @return
	 */
	private boolean isExcludeUri(String requestUri) {
		for (Pattern pattern : excludeUris) {
			Matcher matcher = pattern.matcher(requestUri);
			if (matcher.matches()) {
				return true;
			}
		}
		return false;
	}
}